#include "levent.h"
#include <QApplication>
#include <QThread>

QEvent::Type LEvent::m_eventType = (QEvent::Type)QEvent::registerEventType();

LEvent::LEvent(int msg, const QVariant params/* = QVariant()*/, long& rst/* = s_rst*/)
    : QEvent(m_eventType), m_message(msg), m_params(params), m_rst(rst)
{

}

LEvent::~LEvent()
{
}

void QPostMessage(QObject* obj, int msg, QVariant params)
{
    QCoreApplication::postEvent(obj, new LEvent(msg, params));
}

long QSendMessage(QObject* obj, int msg, QVariant params)
{
    long lResult = 0;
    if (obj->thread() == QThread::currentThread())
    {
        //事件队列不会删除事件。通常的方法是在栈上创建事件
        LEvent e(msg, params, lResult);
        QCoreApplication::sendEvent(obj, &e);
    }
    else
    {
        //事件队列将获得事件的所有权并在事件发送后删除它。必须在堆上创建事件
        LEvent* e = new LEvent(msg, params, lResult);
        QCoreApplication::postEvent(obj, e, Qt::HighEventPriority);
        QEventLoop loop;
        // 当事件处理完毕后，事件实例会被销毁，通知loop退出事件循环
        QObject::connect(e, SIGNAL(destroyed(QObject*)), &loop, SLOT(quit()));
        loop.exec(QEventLoop::ExcludeUserInputEvents);
    }
    return lResult;
}
